import os
import subprocess
import time

import cv2
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer


class NewFileHandler(FileSystemEventHandler):
    def __init__(self, detect_py_path, weights_path, target_dir):
        self.detect_py_path = detect_py_path
        self.weights_path = weights_path
        self.target_dir = target_dir

    def on_created(self, event):
        if not event.is_directory and event.src_path.startswith(self.target_dir):
            print(f"New file detected: {event.src_path}")
            self.run_detect_py()

    def run_detect_py(self):
        save_path = 'D:\\desktop\\2'
        label_txt = 'D:\\desktop\\1.txt'
        cmd_args = [
            'python',
            self.detect_py_path,
            '--weights', self.weights_path,
            '--source', self.target_dir,
            '--save-txt', label_txt  # 添加这个参数来保存文本标注文件
            # 可以继续添加其他参数... # 如果需要保存文本标注文件
            # 可以继续添加其他参数...
        ]
        try:
            result = subprocess.run(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            if result.stderr:
                print(f"Error occurred:\n{result.stderr}")
            if result.stdout:
                print(f"Detector results:\n{result.stdout}")

                # 删除目标目录下的所有图像文件（请谨慎使用，确保这是您想要的操作）
            if os.path.exists(target_dir):
                for filename in os.listdir(target_dir):
                    file_path = os.path.join(target_dir, filename)
                    try:
                        img_dir = os.path.isfile(file_path) and filename.lower().endswith(
                            ('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp'))

                        if img_dir:
                            # prtSC(img_dir,label_txt)
                            # filename_img = _img + '.jpg'
                            # path = os.path.join(img_dir, filename_img)
                            img = cv2.imread(file_path)  # 读取图片，结果为三维数组
                            filename_label = file_path + '.txt'
                            w = img.shape[1]  # 图片宽度(像素)
                            h = img.shape[0]  # 图片高度(像素)
                            n = 1
                            # 打开文件，编码格式'utf-8','r+'读写
                            with open(os.path.join(file_path, filename_label), "r+", encoding='utf-8',
                                      errors="ignor") as f:
                                for line in f:
                                    msg = line.split(" ")  # 根据空格切割字符串，最后得到的是一个list
                                    x1 = int((float(msg[1]) - float(msg[3]) / 2) * w)  # x_center - width/2
                                    y1 = int((float(msg[2]) - float(msg[4]) / 2) * h)  # y_center - height/2
                                    x2 = int((float(msg[1]) + float(msg[3]) / 2) * w)  # x_center + width/2
                                    y2 = int((float(msg[2]) + float(msg[4]) / 2) * h)  # y_center + height/2
                                    filename_last = file_path + "_" + str(n) + ".jpg"
                                    print(filename_last)
                                    img_roi = img[y1:y2, x1:x2]  # 剪裁，roi:region of interest
                                    cv2.imwrite(os.path.join(save_path, filename_last), img_roi)
                                    n = n + 1
                            # os.remove(file_path)
                            print(f"Removed file: {file_path}")
                    except Exception as e:
                        print(f"Error removing file {file_path}: {e}")

        except Exception as e:


01
print(f"An error occurred while running detect.py: {e}")

detect_py_path = 'D:/yolov5-master/detect.py'
weights_path = 'D:/yolov5-master/runs/train/exp67/weights/best.pt'
target_dir = 'D:/yolov5-master/data/images'

# 运行检测并删除图像    # 实例化事件处理器并调用run_detect_py方法
event_handler = NewFileHandler(detect_py_path, weights_path, target_dir)

# 实例化观察者并设置要监控的目录
observer = Observer()
observer.schedule(event_handler, target_dir, recursive=False)

# 启动观察者
observer.start()

try:
    # 等待监控事件
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    # 如果用户按下Ctrl+C，则停止观察者
    observer.stop()

# 等待观察者线程结束
observer.join()
